/*
 * @Author: delin66
 * @Date: 2024-12-01 18:04:42
 * @LastEditors: delin66
 * @LastEditTime: 2025-06-04 17:53:44
 * @Descripttion: 
 */
import { useUserStore } from '@/store/user';
import { getToken } from '@/utils/storage';
import axios from 'axios';
import { ElMessage } from 'element-plus'; 
import nprogress from 'nprogress';
import 'nprogress/nprogress.css';


const request = axios.create({
  baseURL: '/api',
  timeout: 100000,
  withCredentials: true,
});

// 请求拦截器
request.interceptors.request.use((config) => {
  config.headers.Authorization = getToken();
  nprogress.start();
  return config;
});

// 响应拦截器
request.interceptors.response.use(
  (res: any) => {
    nprogress.done();
    if (res.data.code === 401) {
      ElMessage.closeAll();
      ElMessage({
        message: res.data.msg + '，请重新登录',
        type: 'error',
      });
      useUserStore().logout();
      window.location.hash = '/login';
    }
    if (res.data.code !== 200) {
      ElMessage({
        message: res.data.msg || '请求失败',
        type: 'error',
      });
    }
    return res.data;
  },
  (err) => {
    nprogress.done();
    console.log('request.interceptors.response err', err);
    ElMessage({
      message: err.message || '网络错误',
      type: 'error',
    });
    return Promise.reject(err);
  }
);

export default request;
